<?php

class openapi_api_function_v1_business extends openapi_api_function_abstract implements openapi_api_function_interface{

    public function goods_order_list($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $res = kernel::single('b2c_api_site_member',$member_id)->goods_order_list($params['name'],$params['bn'],$params['nPage'],$params['hide_no_store']);
        if(empty($res)){
            return $this->apiData(false,null,400,app::get('b2c')->_('没有更多了'));
        }
        return $this->apiData(true,kernel::single('openapi_utils_datahelper')->array_merge_fb($res),200);
    }

    public function substore_purchase_scope($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $params['nPage'] = empty($params['nPage'])?1:$params['nPage'];
        $res = kernel::single('b2c_api_site_member',$member_id)->substore_purchase_scope($params['substore_id'],$params['nPage']);
        
        if(empty($res['goods']) && empty($res['substoremangers'])){
            return $this->apiData(false,null,400,app::get('b2c')->_('没有更多了'));
        }
        $result = array();
        if(!empty($res['goods'])){
            $goods = array();
            foreach ($res['goods'] as $key => $good) {
                $g = array();
                $g['goods_id'] = $good['goods_id'];
                $g['bn'] = $good['bn'];
                $g['name'] = $good['name'];
                $g['price'] = $good['price'];
                $image_default_url = kernel::single('openapi_utils_image')->getimgbyid($good['image_default_id']);
                $g['image_default_url'] = $image_default_url['url'];
                $goods[] = $g;
            }
            $result['goods'] = $goods;
            $result['store_id'] = $res['store_id'];
            $result['goods_id_divided'] = array_merge($res['goods_id_divided']);
        }
        if(!empty($res['substoremangers'])){
            $storelist = array();
            foreach ($res['substoremangers'] as $key => $storemanger) {
                $sm = array();
                $sm['store_id'] = $storemanger['store_id'];
                $sm['shop_name'] = $storemanger['shop_name'];
                $sm['store_idcardname'] = $storemanger['store_idcardname'];
                $sm['store_name'] = $storemanger['store_name'];
                $sm['area'] = $storemanger['area'];
                $sm['addr'] = $storemanger['addr'];
                $storelist[] = $sm;
            }
            $result['storelist'] = $storelist;
        }
        $result['pager'] = $res['pager'];
        return $this->apiData(true,$result,200);
    }

    public function divideShop($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $store = app::get('business')->model('storemanger')->getList('store_id',array('account_id'=>$member_id));
        $params['nPage'] = empty($params['nPage'])?1:$params['nPage'];
        $res = kernel::single('b2c_api_site_member',$member_id)->divideShop($params,$store[0]['store_id'],$err_msg);
        if(!$res){
            return $this->apiData(false,null,400,$err_msg);
        }
        return $this->apiData(true,null,200,$err_msg);
    }

    public function godelivery($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $res = kernel::single('business_api_site_order',$member_id)->godelivery($params['order_id'],$err_msg);
        foreach ($res['arrItems'] as $key => &$items) {
            unset($items['addon']);
            $items['store'] = $items['products']['store'];
            unset($items['products']);
            $items['product_attr'] = array_merge($items['minfo']['product_attr']);
            unset($items['minfo']);
        }
        $order = array();
        $order['order_id'] = $res['order']['order_id'];
        $order['total_amount'] = $res['order']['total_amount'];
        $order['discount_value'] = $res['order']['discount_value'];
        $order['pay_status'] = $res['order']['pay_status'];
        $order['ship_status'] = $res['order']['ship_status'];
        $order['is_delivery'] = $res['order']['is_delivery'];
        $order['createtime'] = $res['order']['createtime'];
        $order['last_modified'] = $res['order']['last_modified'];
        $order['member_id'] = $res['order']['member_id'];
        $order['status'] = $res['order']['status'];
        $order['confirm'] = $res['order']['confirm'];
        $order['itemnum'] = $res['order']['itemnum'];
        $order['cost_shipping'] = $res['order']['shipping']['cost_shipping'];
        $order['memo'] = $res['order']['memo'];
        $order['consignee'] = $res['order']['consignee'];
        $result['order'] = $order;
        foreach ($res['arrItems'] as $key => &$item) {
            $item['needsend'] = intval($item['needsend']);
        }
        $result['arrItems'] = $res['arrItems'];
        $result['corplist'] = $res['corplist'];
        if(!$res){
            return $this->apiData(false,null,400,$err_msg);
        }
        return $this->apiData(true,$result,200,app::get('b2c')->_('发货成功'));
    }

    public function dodelivery($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $store_info = app::get('business')->model('storemanger')->getList('store_id',array('account_id'=>$member_id));
        $store_id = $store_info[0]['store_id'];
        $params['delivery'] = 1;
        $params['money'] = 0;
        $params['is_protect'] = false;
        $send = array();
        foreach ($params['send_items'] as $key => $item) {
            $send[$item['item_id']] = $item['sendnum'];
        }
        $params['send'] = $send;
        unset($params['send_items']);
        $res = kernel::single('business_api_site_order',$member_id)->dodelivery($params,$err_msg);
        if(!$res){
            return $this->apiData(false,null,400,$err_msg);
        }
        //设置为确认状态
        $obj_order = app::get('b2c')->model('orders');
        $sdf_order = $obj_order->dump(array('order_id'=>$params['order_id'], 'store_id'=>$store_id), '*');
        if($sdf_order){
            $sdf_order['confirm_status'] = '1';
            $obj_order->save($sdf_order);
        }
        return $this->apiData(true,null,200,$err_msg);
    }

    public function substore_purchase_price($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $store_id = app::get('business')->model('storemanger')->getList('store_id',array('account_id'=>$member_id));
        $res = kernel::single('b2c_api_site_member',$member_id)->substore_purchase_price($params, $aData, $msg);
        if(!$res){
            return $this->apiData(false,null,400,app::get('b2c')->_('没有更多了'));
        }
        return $this->apiData(true,kernel::single('openapi_utils_datahelper')->array_merge_fb($aData),200);
    }

    public function set_substore_purchase_price($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }

        $res = kernel::single('b2c_api_site_member',$member_id)->set_substore_purchase_price($params['price'], $msg);
        if(!$res){
            return $this->apiData(false,null,400,$msg);
        }
        return $this->apiData(true,null,200,$msg);
    }

    public function order_to_ship($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        if(isset($params['nPage']) && $params['nPage'] != null && intval($params['nPage'])<1){
            return $this->apiData(false,null,400,app::get('b2c')->_('参数错误'));
        }
        $res = kernel::single('b2c_api_site_member',$member_id)->seller_order('ship','','','','all','',$params['nPage']);
        if(empty($res)){
            return $this->apiData(false,null,400,app::get('b2c')->_('没有更多了'));
        }elseif(isset($res['pager']) && !empty($res['pager'])){
            if(intval($res['pager']['current'])>intval($res['pager']['total'])){
                return $this->apiData(false,null,400,app::get('b2c')->_('没有更多了'));
            }
        }
        return $this->apiData(true,kernel::single('openapi_utils_datahelper')->array_merge_fb($res),200);
    }

    public function order_nopayed($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        if(isset($params['nPage']) && $params['nPage'] != null && intval($params['nPage'])<1)
            return $this->apiData(false,null,400,app::get('b2c')->_('参数错误'));
        $res = kernel::single('b2c_api_site_member',$member_id)->seller_order('nopayed','','','','all','',$params['nPage']);
        if(empty($res)){
            return $this->apiData(false,null,400,app::get('b2c')->_('没有更多了'));
        }elseif(isset($res['pager']) && !empty($res['pager'])){
            if(intval($res['pager']['current'])>intval($res['pager']['total']))
                return $this->apiData(false,null,400,app::get('b2c')->_('没有更多了'));
        }
        return $this->apiData(true,kernel::single('openapi_utils_datahelper')->array_merge_fb($res),200);
    }


    public function order_docancel($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $res = kernel::single('b2c_api_site_member',$member_id)->order_docancel($params['order_id'], $msg);
        if(!$res){
            return $this->apiData(false,null,400,$msg);
        }
        return $this->apiData(true,null,200, $msg);
    }

    public function change_price_before($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $storeInfo = app::get('business')->model('storemanger')->getRow('store_id',array('account_id'=>$member_id));
        $res = kernel::single('business_api_site_order',$member_id)->change_price_before($params,$err_msg);
        $res['cost_shipping'] = $res['orders']['shipping']['cost_shipping'];
        if($res['orders']['store_id']==$storeInfo['store_id']){
            $result['cost_item'] = $res['orders']['cost_item'];
            $result['total_amount'] = $res['orders']['total_amount'];
            $result['discount_value'] = $res['orders']['discount_value'];
            $result['seller_discount_value'] = $res['orders']['seller_discount_value'];
            $result['cost_shipping'] = $res['orders']['shipping']['cost_shipping'];
            $result['order_id'] = $res['order_id'];
            return $this->apiData(true,$result,200,$err_msg);
        }else{
            return $this->apiData(false,null,400,app::get('b2c')->_('无权修改价格'));
        }
    }

    public function change_price($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $storeInfo = app::get('business')->model('storemanger')->getRow('store_id',array('account_id'=>$member_id));
        $order = app::get('b2c')->model('orders')->dump(array('order_id'=>$params['order_id']));
        if($storeInfo['store_id'] != $order['store_id']){
            return $this->apiData(false,null,400,app::get('b2c')->_('无权修改价格'));
        }
        if($order['order_type']!='normal'){
            return $this->apiData(false,null,400,app::get('b2c')->_('活动订单不可修改价格'));
        }
        if(!is_numeric($params['final_amount']) || floatval($params['final_amount'])<0){
            return $this->apiData(false,null,400,app::get('b2c')->_('订单金额错误'));
        }
        //修改价格
        if($order['pay_status']=='0'){
            $orderdata = array();
            $orderdata['order_id'] = $order['order_id'];
            $orderdata['seller_discount_value'] = floatval($params['final_amount']) - floatval($order['total_amount']);
            $orderdata['final_amount'] = $params['final_amount'];
            app::get('b2c')->model('orders')->update($orderdata,array('order_id'=>$_POST['order_id']));
            return $this->apiData(true,array('final_amount'=>$orderdata['final_amount']),200,app::get('b2c')->_('订单金额修改成功！'));
        }else{
            return $this->apiData(false,null,400,app::get('b2c')->_('非未支付订单不可修改价格'));
        }
    }

    //经销商审核列表接口  by zhuhao
    public function substore_approve_list($params,&$code,&$sub_msg){
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $res = kernel::single('b2c_api_site_member',$member_id)->substore_approve_list($params, $aData, $msg);
        if(!$res){
            return $this->apiData(false,null,400,$msg);
        }
        return $this->apiData(true,kernel::single('openapi_utils_datahelper')->array_merge_fb($aData),200, $msg);
    }

    //经销商审核详细接口  by zhuhao
    public function substore_approve_detail($params,&$code,&$sub_msg){
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $res = kernel::single('b2c_api_site_member',$member_id)->substore_approve_detail($params, $aData, $msg);
        if(!$res){
            return $this->apiData(false,null,400,$msg);
        }
        return $this->apiData(true,kernel::single('openapi_utils_datahelper')->array_merge_fb($aData),200, $msg);
    }

    //经销商审核接口  by zhuhao
    public function substore_approve($params,&$code,&$sub_msg){
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $res = kernel::single('b2c_api_site_member',$member_id)->substore_approve($params, $aData, $msg);
        if(!$res){
            return $this->apiData(false,null,400,$msg);
        }
        return $this->apiData(true,kernel::single('openapi_utils_datahelper')->array_merge_fb($aData),200, $msg);
    }

    public function goods_instock_list($params,&$code,&$sub_msg){
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $res = kernel::single('b2c_api_site_member',$member_id)->goods_instock_list($params, $aData, $msg);
        if(!$res){
            return $this->apiData(false,null,400,$msg);
        }
        return $this->apiData(true,kernel::single('openapi_utils_datahelper')->array_merge_fb($aData),200, $msg);
    }

    public function set_goods_instock_status($params,&$code,&$sub_msg){
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $res = kernel::single('b2c_api_site_member',$member_id)->set_goods_instock_status($params, $aData, $msg);
        if(!$res){
            return $this->apiData(false,null,400,$msg);
        }
        return $this->apiData(true,null,200, $msg);
    }

    public function substore_favorite($params,&$code,&$sub_msg){
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $res = kernel::single('b2c_api_site_member',$member_id)->sub_favorite($params, $aData, $msg);
        if(!$res){
            return $this->apiData(false,null,400,$msg);
        }
        return $this->apiData(true,kernel::single('openapi_utils_datahelper')->array_merge_fb($aData),200);
    }

    public function sub_goods_instock($params,&$code,&$sub_msg){
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $res = kernel::single('b2c_api_site_member',$member_id)->sub_goods_instock($params, $aData, $msg);
        if(!$res){
            return $this->apiData(false,null,400,$msg);
        }
        return $this->apiData(true,kernel::single('openapi_utils_datahelper')->array_merge_fb($aData),200, $msg);
    }

    
    public function store_goods_list($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $store = app::get('business')->model('storemanger')->getList("store_id",array('account_id'=>$member_id));
        $store_id = $store[0]['store_id'];
        $npage = empty($params['npage'])?1:$params['npage'];
        $pagesize = empty($params['pagesize'])?10:$params['pagesize'];
        $products_sql = "SELECT s.*,p.name,p.bn pbn,p.spec_info,g.bn gbn,g.combined FROM " . DB_PREFIX . "b2c_goods_store s," . DB_PREFIX . "b2c_products p," . DB_PREFIX . "b2c_goods g WHERE s.product_id=p.product_id and p.goods_id=g.goods_id and s.store_id='".$store_id."'";
        if($params['hide_no_store']){
            $products_sql .= " and s.store>0";
        }
        if(!empty($params['search_content'])){
            $products_sql .= " and (p.name like '%".$params['search_content']."%' or p.bn like '%".$params['search_content']."%' or g.bn like '%".$params['search_content']."%')";
        }
        $products_sql .= " limit ".($npage-1)*$pagesize.",".$pagesize;
        $products = kernel::database()->select($products_sql);
        if(empty($products)){
            return $this->apiData(false,null,400,app::get('b2c')->_('没有更多了'));
        }

        $store_goods = app::get('business')->model('goods');
        $substore_price = array();
        foreach ($products as $key => &$p) {
            unset($p['mktprice']);
            unset($p['marketable']);
            unset($p['store_grade']);
            unset($p['last_modify']);
            unset($p['disabled']);
            if(!empty($p['spec_info'])){
                $p['name'] = $p['name']." ".$p['spec_info'];
            }
            unset($p['spec_info']);
            if($substore_price[$p['gbn']]){
                $p['subinfo'][] = array(
                    'subprice'=>$subprice['price'],
                    'grade_id'=>$subprice['grade_id'],
                    'grade_name'=>$subprice['grade_name'],
                    'limit_price'=>$subprice['limit_price'],
                );
                $p['img_url'] = $substore_price[$p['gbn']][$p['product_id']]['img_url'];
            }else{
                $aData = array();
                $res = kernel::single('b2c_api_site_member',$member_id)->substore_purchase_price(array('svalue'=>$p['gbn']), $aData, $msg);
                if($res){
                    foreach ($aData['sub_storeprice'] as $key => $subprice) {
                        $substore_price[$p['gbn']][$subprice['product_id']] = array('price'=>$subprice['price'],'limit_price'=>$subprice['limit_price'],'img_url'=>$subprice['img_url']);
                        if($p['product_id']==$subprice['product_id']){
                            $p['img_url'] = $subprice['img_url'];
                        }
                    }
                }
            }
            //采购在途
            $p['purchase_num'] = $store_goods->get_purchase_num($p['product_id'],$member_id);
            //销售在途
            $p['onsale_num'] = $store_goods->get_onsale_num($p['product_id'],$store_id);
            $p['subinfo'] = $this->get_sub_price($p['product_id'],$store_id);
            $price = array();
            foreach ($p['subinfo'] as $v) {
                $price[] = $v['subprice'];
            }
            $p['max_price'] = max($price);
            $p['min_price'] = min($price);

            $tmp_dlytype = app::get('business')->model('goods')->get_dlytype($p['goods_id'], $store_id);
            if(empty($tmp_dlytype)){
                $tmp_dlytype = app::get('b2c')->model('dlytype')->getList('dt_name',array('store_id'=>$store_id));
                $p['dt_name'] = $tmp_dlytype[0]['dt_name'];
            }else{
                $p['dt_name'] = $tmp_dlytype[0]['dt_name'];
            }
            $p['sub_store_num'] = $this->get_sub_goods_store_num($p['product_id'],$p['store_id']);
        }
        return $this->apiData(true,$products,200);
    }
    //得到下级的采购价和限价
    public function get_sub_price($product_id,$store_id){
        $mdl_storemanger = app::get('business')->model('storemanger');
        $mdl_storegrade = app::get('business')->model('storegrade');
        $mdl_sub_storegrade_price = app::get('business')->model('sub_storegrade_price');
        $mdl_goods_price_grade_limit = app::get('b2c')->model('goods_price_grade_limit');
        $storeinfo = $mdl_storemanger->getRow('store_grade',array('store_id'=>$store_id));
        $subinfo = array();
        $sub_storegrade = $mdl_storegrade->getList('grade_id,grade_name',array('parent_id'=>$storeinfo['store_grade']));
        foreach ($sub_storegrade as $key => $value) {
            $sub_price = $mdl_sub_storegrade_price->getList('price',array('product_id'=>$product_id,'store_id'=>$store_id,'store_grade'=>$value['grade_id']));
            $limit_price = $mdl_goods_price_grade_limit->getRow('limit_price',array('product_id'=>$product_id,'grade_id'=>$value['grade_id']));
            if(!$sub_price){
                $data['product_id'] = $product_id;
                $data['store_id'] = $store_id;
                $data['store_grade'] = $value['grade_id'];
                $data['price'] = $limit_price['limit_price'];
                if($mdl_sub_storegrade_price->save($data)){
                    $sub_price = $mdl_sub_storegrade_price->getList('*',array('store_id'=>$store_id, 'store_grade'=>$value['grade_id'], 'product_id'=>$product_id));
                }
            }   
            if($sub_price){
                $subinfo[$key]['grade_id'] = $value['grade_id'];
                $subinfo[$key]['grade_name'] = $value['grade_name'];
                $subinfo[$key]['subprice'] = $sub_price[0]['price'];
                $subinfo[$key]['limit_price'] = $limit_price['limit_price'];
            }
        }
        return $subinfo;
    }

    
    public function get_sub_goods_store_num($product_id,$store_id)
    {
        $sub_store = app::get('business')->model('storemanger')->getList("store_id",array('parent_id'=>$store_id));
        if(empty($sub_store)) return 0;
        $sub_store_id = array();
        foreach ($sub_store as $key => $store) {
            $sub_store_id[] = $store['store_id'];
        }
        $store_num = app::get('b2c')->model('goods_store')->getList('sum(store) store_num',array('product_id'=>$product_id,'store_id|in'=>$sub_store_id));
        return intval($store_num[0]['store_num']);
    }

    
    public function store_goods_detail($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $npage = empty($params['npage'])?1:$params['npage'];
        $pagesize = empty($params['pagesize'])?10:$params['pagesize'];
        // $product = app::get('b2c')->model('products')->getList("*",array('product_id'=>$params['product_id']));
        // $goods = app::get('b2c')->model('goods')->dump(array('goods_id'=>$product[0]['goods_id']));
        // $result['goods_id'] = $product[0]['goods_id'];
        // $result['product_id'] = $params['product_id'];
        // $result['product_name'] = $product[0]['name']." ".$product[0]['spec_info'];
        $items = app::get('b2c')->model('goods_store_log')->getList('*', array('store_id'=>$params['store_id'], 'product_id'=>$params['product_id']),($npage-1)*$pagesize,$pagesize,"mtime desc");
        if(empty($items)){
            $msg = $npage>1?'没有更多了':'暂无数据';
            return $this->apiData(false,null,400,app::get('b2c')->_($msg));
        }
        return $this->apiData(true,$items,200);
    }

    
    function set_sub_price($params,&$code,&$sub_msg){
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $store = app::get('business')->model('storemanger')->getList("store_id,store_grade",array('account_id'=>$member_id));
        $store_id = $store[0]['store_id'];

		$subinfo = $params['subinfo'];
        if(isset($params['product_id']) && $subinfo){
			foreach($subinfo as $value){
				$sub_price = floatval($value['subprice']);
				$limit_price = floatval($value['limit_price']);
				if($limit_price > 0 && $sub_price > $limit_price || $sub_price < 0){
					return $this->apiData(false, null, 400, app::get('b2c')->_('价格设置有误，请重新设置'));
				}else{
					$data['store_id'] = $store_id;
					$data['product_id'] = $params['product_id'];
					$data['store_grade'] = $value['grade_id'];
					$data['price'] = $sub_price;
					if(app::get('business')->model('sub_storegrade_price')->save($data)){
						$sub_store_list = app::get('business')->model('storemanger')->getList('store_id', array('parent_id'=>$store_id));
						$sub_store_id = array();
						foreach($sub_store_list as $s){
							$sub_store_id[] = $s['store_id'];
						}
						$rs = app::get('b2c')->model('goods_store')->update(array('price'=>$sub_price), array('store_id|in'=>$sub_store_id, 'store_grade'=>$value['grade_id'], 'product_id'=>$params['product_id']));
					}else{
						return $this->apiData(false, null, 400, app::get('b2c')->_('设置失败'));
					}
				}
			}
            return $this->apiData(true, null, 200, app::get('b2c')->_('设置成功'));
        }
        return $this->apiData(false,null,400,app::get('b2c')->_('参数错误'));
    }

    
    function adjust_number_onsale($params,&$code,&$sub_msg){
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $store = app::get('business')->model('storemanger')->getList("store_id,store_grade",array('account_id'=>$member_id));
        $store_id = $store[0]['store_id'];

        if(isset($params['product_id']) && isset($params['num'])){
            $num = intval($params['num']);
            $mdl_goods_store = app::get('b2c')->model('goods_store');
            $goods_store = $mdl_goods_store->dump(array('product_id'=>$params['product_id'], 'store_id'=>$store_id));
            $goods_store['store_onsale'] = $num;
            if($goods_store['store_onsale'] < 0){
                return $this->apiData(false, null, 400, app::get('b2c')->_('上架数量不能小于0'));
            }elseif($goods_store['store_onsale'] > $goods_store['store']){
                return $this->apiData(false, null, 400, app::get('b2c')->_('上架数量不能大于库存'));
            }else{
                $store_dly=app::get('b2c')->model('dlytype')->getList('dt_id',array('store_id'=>$store_id,'dt_status'=>'1'));
                if(empty($store_dly)){
                    return $this->apiData(false, null, 400, app::get('b2c')->_('请先设置运费模板'));
                }else{
                    if($mdl_goods_store->save($goods_store)){
                        return $this->apiData(true, null, 200, app::get('b2c')->_('操作成功'));
                    }else{
                        return $this->apiData(false, null, 400, app::get('b2c')->_('操作失败'));
                    }
                }
            }
        }
        return $this->apiData(false,null,400,app::get('b2c')->_('参数错误'));
    }

    
    public function goods_substore_purchase_scope($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $store = app::get('business')->model('storemanger')->getList("store_id,store_grade",array('account_id'=>$member_id));
        $store_id = $store[0]['store_id'];
        $goods_id = $params['goods_id'];
        $npage = $params['npage']?$params['npage']:1;
        $pagesize = $params['pagesize']?$params['pagesize']:10;

        $mdl_goods_store = app::get('b2c')->model('goods_store');
        $mdl_goods = app::get('b2c')->model('goods');
        $mdl_goods_cat = app::get('b2c')->model('goods_cat');
        $mdl_account = app::get('pam')->model('account');
        $sub_store_list = app::get('business')->model('storemanger')->getList('store_id,shop_name,store_idcardname,store_name,area', array('parent_id'=>$store_id),($npage-1)*$pagesize,$pagesize,"store_id asc");
        if(empty($sub_store_list)){
            return $this->apiData(false,null,400,app::get('b2c')->_('没有更多了'));
        }
        foreach($sub_store_list as $k=>$v){
            $purchase_scope = $mdl_goods_store->dump(array('goods_id'=>$goods_id, 'store_id'=>$v['store_id']),'disabled');
            if($purchase_scope['disabled']=='false'){
                $goods = $mdl_goods->dump($goods_id, 'cat_id');
                $cat_id = $goods['category']['cat_id'];
                $goods_cat = $mdl_goods_cat->dump($cat_id, 'parent_id');
                while($goods_cat['parent_id'] != '0'){
                    $cat_id = $goods_cat['parent_id'];
                    $goods_cat = $mdl_goods_cat->dump($cat_id, 'parent_id');
                }

                if(in_array($cat_id, explode(',', $v['store_region']))){
                    if(kernel::single('b2c_goods_store')->goodsBindStore($goods_id, array($v['store_id']), $msg)){
                        $purchase_scope = $mdl_goods_store->dump(array('goods_id'=>$goods_id, 'store_id'=>$v['store_id']), 'disabled');
                    }
                }
            }
            $area = explode(":", $v['area']);
            $sub_store_list[$k]['area'] = $area[1];
            $sub_store_list[$k]['purchase_scope'] = ($purchase_scope['disabled'] == 'false');
        }
        $result['sub_store'] = $sub_store_list;
        return $this->apiData(true,$result,200);
    }

    
    public function set_goods_substore_purchase($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $store = app::get('business')->model('storemanger')->getList("store_id,store_grade",array('account_id'=>$member_id));
        $store_id = $store[0]['store_id'];

        $sub_store_list = app::get('business')->model('storemanger')->getList('store_id', array('parent_id'=>$store_id));
        $sub_store_id = array();
        foreach($sub_store_list as $s){
            $sub_store_id[] = $s['store_id'];
        }
        if(empty($params['content'])){
            return $this->apiData(false,null,400,app::get('b2c')->_('您未做任何修改'));
        }
        foreach ($params['content'] as $key => $st) {
            if(in_array($st['store_id'], $sub_store_id)){
                $disabled = $st['status']=='1'?'false':'true';
                app::get('b2c')->model('goods_store')->update(array('disabled'=>$disabled), array('goods_id'=>$params['goods_id'], 'store_id'=>$st['store_id']));
            }
        }

        return $this->apiData(true, null, 200, app::get('business')->_('设置成功'));
    }

    
    public function sub_store_goods_list($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $store = app::get('business')->model('storemanger')->getList("store_id,store_grade",array('account_id'=>$member_id));
        $store_id = $store[0]['store_id'];
        $this->get_sub_store($store_id,$sub_store_list,$sub_store_ids);
        $npage = empty($params['npage'])?1:$params['npage'];
        $pagesize = empty($params['pagesize'])?10:$params['pagesize'];
        $db = kernel::database();

        $limit_sql = "select distinct p.product_id from " . DB_PREFIX . "b2c_goods_store s left join " . DB_PREFIX . "b2c_goods g on s.goods_id=g.goods_id left join " . DB_PREFIX . "b2c_products p on s.product_id=p.product_id left join " . DB_PREFIX . "business_storemanger st on s.store_id=st.store_id ";
        $limit_sql .= "where s.store_id in ('".implode("','", $sub_store_ids)."') ";
        if(!empty($params['search_content'])){
            $limit_sql .= "and (g.bn like '%".$params['search_content']."%' or p.bn like '%".$params['search_content']."%' or st.store_name like '%".$params['search_content']."%' or g.name like '%".$params['search_content']."%')";
        }
        if($params['hide_no_store']){
            $limit_sql .= " and s.store>0";
        }
        $limit_sql .= " order by p.product_id asc limit ".($npage-1)*$pagesize.",".$pagesize;
        $product_ids = app::get('b2c')->model('goods_store')->db->select($limit_sql);
        if(empty($product_ids)){
            $msg = $npage>1?"没有更多了":"暂无数据";
            return $this->apiData(false,null,400,app::get('b2c')->_($msg));
        }
        $limit_pid = array();
        foreach ($product_ids as $key => $pid) {
            $limit_pid[] = $pid['product_id'];
        }
        $sql = "select s.goods_id,s.product_id,g.bn gbn,p.bn pbn,g.name,p.spec_info,g.image_default_id,s.store_id,st.parent_id,s.store_grade,st.store_name,st.account_id,s.price,s.store,s.store_onsale";
        $sql .= " from " . DB_PREFIX . "b2c_goods_store s left join " . DB_PREFIX . "b2c_goods g on s.goods_id=g.goods_id left join " . DB_PREFIX . "b2c_products p on s.product_id=p.product_id left join " . DB_PREFIX . "business_storemanger st on s.store_id=st.store_id ";
        $sql .= "where s.store_id in ('".implode("','", $sub_store_ids)."') ";
        if(!empty($params['search_content'])){
            $sql .= "and (g.bn like '%".$params['search_content']."%' or p.bn like '%".$params['search_content']."%' or st.store_name like '%".$params['search_content']."%' or g.name like '%".$params['search_content']."%')";
        }
        if($params['hide_no_store']){
            $sql .= " and s.store>0";
        }
        $sql .= " and s.product_id in ('".implode("','",$limit_pid)."') order by s.store_grade asc";
        $res = $db->select($sql);
        $price_limit = app::get('b2c')->model('goods_price_grade_limit');
        $store_goods = app::get('business')->model('goods');
        //采用PC端编号规则
        $sub2sup = array();
        $storemangers = app::get('business')->model('storemanger')->getList('store_id,parent_id');
        foreach($storemangers as $v){
            if($v['parent_id'])
                $sub2sup[$v['store_id']] = $v['parent_id'];
        }
        asort( $sub2sup);
        $temp_id =array();
        $i = 1;
        $all_store_id = array($store_id);
        do{
            $sub_store_id_tmp = array();
            $j = 1;
            $last_v;
            foreach($sub2sup as $k=>$v){
                if(in_array($v, $all_store_id) && !in_array($k, $all_store_id)){
                    if(empty($last_v) || $last_v != $v){
                        $j = 1;
                    }
                    $last_v = $v;
                    if($i == 1){
                        $str = ''.($j++);
                    }else {
                        $str_key = array_search($v, $temp_id);
                        $str = $str_key.'.'.($j++);
                    }
                    $temp_id[$str] = $k;
                    $sub_store_id_tmp[] = $k;
                }
            }
            $all_store_id = array_merge($all_store_id,$sub_store_id_tmp);
            $i++;
        }while(!empty($sub_store_id_tmp)); 
        $sub_store_id = $temp_id;
        //编号规则结束
        $list = array();
        $store_bn = array();
        $has_bn_store = array();
        foreach ($res as $key => $p) {
            $p['image_url'] = base_storager::image_path($p['image_default_id'],'m');
            $plimit = $price_limit->getList("limit_price",array('goods_id'=>$p['goods_id'],'product_id'=>$p['product_id'],'grade_id'=>$p['store_grade']));
            $list[$p['product_id']]['goods_id'] = $p['goods_id'];
            $list[$p['product_id']]['product_id'] = $p['product_id'];
            $list[$p['product_id']]['gbn'] = $p['gbn'];
            $list[$p['product_id']]['pbn'] = $p['pbn'];
            $list[$p['product_id']]['name'] = $p['name'];
            $list[$p['product_id']]['spec_info'] = $p['spec_info'];
            $list[$p['product_id']]['image_default_id'] = $p['image_default_id'];
            $list[$p['product_id']]['image_url'] = $p['image_url'];
            $store = array();
            $store['store_id'] = $p['store_id'];
            $store['parent_id'] = $p['parent_id'];
            $store['store_grade'] = $p['store_grade'];
            $store['store_name'] = $p['store_name'];
            $store['price'] = $p['price'];
            $store['limit_price'] = $plimit[0]['limit_price'];
            $store['store'] = intval($p['store']);
            $store['store_onsale'] = intval($p['store_onsale']);
            //采购在途
            $store['purchase_num'] = $store_goods->get_purchase_num($p['product_id'],$p['account_id']);
            //销售在途
            $store['onsale_num'] = $store_goods->get_onsale_num($p['product_id'],$p['store_id']);
            //经销商编号
            $store_bn[$p['product_id']]['store_grade'] = $store_bn[$p['product_id']]['store_grade']?$store_bn[$p['product_id']]['store_grade']:$store['store_grade'];
            $store_bn[$p['product_id']]['store_bn'] = $store_bn[$p['product_id']]['store_bn']?$store_bn[$p['product_id']]['store_bn']:0;
            // if($store['parent_id']==$store_id){
            //     //给第一层级设置编号
            //     $store_bn[$p['product_id']]['store_bn']++;
            //     $has_bn_store[$p['product_id']][$store['store_id']]['store_bn'] = $store['store_bn'] = $store_bn[$p['product_id']]['store_bn'];
            // }else{
            //     //第二层级开始需根据父级查询
            //     $parent_bn = $has_bn_store[$p['product_id']][$store['parent_id']]['store_bn'];
            //     if(empty($parent_bn)){
            //         $tmp_parent_id = $store['parent_id'];
            //         $tmp_parent_bn = "";
            //         do {
            //             $tmp_store = app::get('business')->model('storemanger')->getRow('store_id,parent_id',array('store_id'=>$tmp_parent_id));
            //             $tmp_parent_id = $tmp_store['parent_id'];
            //             $tmp_parent_bn .= ".1";
            //         } while ($tmp_parent_id != $store_id);
            //         $parent_bn = substr($tmp_parent_bn, 1);
            //     }
            //     $bro_bn = $has_bn_store[$p['product_id']][$store['parent_id']]['bro_bn'];
            //     $bro_bn = $bro_bn?$bro_bn:0;
            //     $bro_bn++;
            //     $store['store_bn'] = $parent_bn.'.'.$bro_bn;
            // }
            $store['store_bn'] = array_search($store['store_id'], $sub_store_id);
            $list[$p['product_id']]['storelist'][] = $store;
        }
        foreach ($list as $key => $value) {
            $sortArr = $value['storelist'];
            $arrSort = array();
            foreach($sortArr AS $uniqid => $row){
                foreach($row AS $k=>$v){
                    $arrSort[$k][$uniqid] = $v;
                }
            }
            array_multisort($arrSort['store_bn'],SORT_ASC, $sortArr);
            $list[$key]['storelist'] = $sortArr;
        }
        $list = array_values($list);
        return $this->apiData(true,$list,200);
    }

    
    function get_sub_store($store_id,&$sub_store_list,&$sub_store_ids)
    {
        $mdl_storemanger = app::get('business')->model('storemanger');
        $sub_store = $mdl_storemanger->getList('store_id,store_name',array('parent_id'=>$store_id));
        if(!empty($sub_store)){
            foreach ($sub_store as $key => &$store) {
                $sub_store_ids[] = $store['store_id'];
                $this->get_sub_store($store['store_id'],$store[$store['store_id']],$sub_store_ids);
            }
            $sub_store_list = $sub_store;
        }
    }

    
    public function sub_store_goods_detail($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $npage = empty($params['npage'])?1:$params['npage'];
        $pagesize = empty($params['pagesize'])?10:$params['pagesize'];
        // $product = app::get('b2c')->model('products')->getList("*",array('product_id'=>$params['product_id']));
        // $goods = app::get('b2c')->model('goods')->dump(array('goods_id'=>$product[0]['goods_id']));
        // $result['goods_id'] = $product[0]['goods_id'];
        // $result['product_id'] = $params['product_id'];
        // $result['product_name'] = $product[0]['name']." ".$product[0]['spec_info'];
        $items = app::get('b2c')->model('goods_store_log')->getList('*', array('store_id'=>$params['store_id'], 'product_id'=>$params['product_id']),($npage-1)*$pagesize,$pagesize,"mtime desc");
        if(empty($items)){
            $msg = $npage>1?'没有更多了':'暂无数据';
            return $this->apiData(false,null,400,app::get('b2c')->_($msg));
        }
        return $this->apiData(true,$items,200);
    }

    
    public function store_info($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $storeinfo = app::get('business')->model('storemanger')->getRow("store_id,store_name,store_idcardname,area,addr,tel,email,parent_id,store_grade,store_region,approved_time",array('store_id'=>$params['store_id']));
        $area = explode(":", $storeinfo['area']);
        $storeinfo['area'] = $area[1];
        $parent = app::get('business')->model('storemanger')->getRow('store_name',array('store_id'=>$storeinfo['parent_id']));
        $storeinfo['parent_name'] = $parent['store_name'];
        $store_grade = app::get('business')->model('storegrade')->getRow('grade_name',array('grade_id'=>$storeinfo['store_grade']));
        $storeinfo['grade_name'] = $store_grade['grade_name'];
        $store_region = app::get('b2c')->model('goods_cat')->getList('cat_name',array('cat_id|in'=>explode(",", substr($storeinfo['store_region'],1,strlen($storeinfo['store_region'])-2))));
        $region_name = null;
        foreach ($store_region as $key => $name) {
            if($region_name) $region_name .= ",";
            $region_name .= $name['cat_name'];
        }
        $storeinfo['region_name'] = $region_name;
        return $this->apiData(true,$storeinfo,200);
    }

    
    public function sub_onsale_order($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        if(!empty($params['store_id'])){
            $store = app::get('business')->model('storemanger')->getRow("account_id",array('store_id'=>$params['store_id']));
            if(!empty($store)){
                $member_id = $store['account_id'];
            }
        }
        if(isset($params['npage']) && $params['npage'] != null && intval($params['npage'])<1){
            return $this->apiData(false,null,400,app::get('b2c')->_('参数错误'));
        }
        $res = kernel::single('b2c_api_site_member',$member_id)->seller_order('onsale','','',$params['gbn'],'all','',$params['npage']);
        if(empty($res)){
            return $this->apiData(false,null,400,app::get('b2c')->_('没有更多了'));
        }elseif(isset($res['pager']) && !empty($res['pager'])){
            if(intval($res['pager']['current'])>intval($res['pager']['total'])){
                return $this->apiData(false,null,400,app::get('b2c')->_('没有更多了'));
            }
        }
        return $this->apiData(true,kernel::single('openapi_utils_datahelper')->array_merge_fb($res),200);
    }

    
    public function salesmanlist($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $res = kernel::single('b2c_api_site_member',$member_id)->salesmanlist($params,$aData, $msg);
        if(!$res){
            return $this->apiData(false,null,200,$msg);
        }
        return $this->apiData(true,kernel::single('openapi_utils_datahelper')->array_merge_fb($aData),200);
    }

    
    public function sub_onpurchase_order($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        if(!empty($params['store_id'])){
            $store = app::get('business')->model('storemanger')->getRow("account_id",array('store_id'=>$params['store_id']));
            if(!empty($store)){
                $member_id = $store['account_id'];
            }
        }
        $type = 'onpurchase';
        $order_id = $params['order_id'];
        $goods_name = $params['goods_name'];
        $goods_bn = $params['goods_bn'];
        $time = $params['time'];
        $nPage = empty($params['page_no'])?1:$params['page_no'];
        $order_type = $params['order_type'];

        $order = app::get('b2c')->model('orders');
        $ctl   = kernel::single('b2c_api_site_member',$member_id);
        
        $order_id = trim($order_id);
        $goods_name = trim($goods_name);
        $goods_bn = trim($goods_bn);

        $sql = $ctl->get_search_order_ids($type,$time,$order_type);
        $arrayorser = $order->db->select($sql);
        $arr;
        if(empty($order_id) && empty($goods_name) && empty($goods_bn)){
            $arr = $arrayorser;
        }else{
            $search_order=$ctl->search_order($order_id,$goods_name,$goods_bn);
            foreach($arrayorser as $key=>$value){
                foreach($search_order as $k=>$v){
                    if($value['order_id']==$v['order_id']){
                        $arr[]=$value;
                    }
                }
            }
        }
        $arrayorser=$arr;
        if(empty($arrayorser)){
            return $this->apiData(false,null,400,app::get('b2c')->_('没有找到相应的订单！'));
        }else{
            $aData = $order->fetchByMember($member_id,$nPage-1,'','',$arrayorser);
        }
        $ctl->get_order_details($aData,'member_orders');
        $oImage = app::get('image')->model('image');
        $imageDefault = app::get('image')->getConf('image.set');
        $applySObj = app::get('spike')->model('spikeapply');
        $applyGObj = app::get('groupbuy')->model('groupapply');
        $applyScoreObj = app::get('scorebuy')->model('scoreapply');
        
        foreach($aData['data'] as $k=>$v) {
            //获取订单支付时间
            $obj_payment = app::get('ectools')->model('refunds');
            $payment_id = $obj_payment->get_payment($v['order_id']);
            $pay_time = app::get('ectools')->model('payments')->getRow('t_payed',array('payment_id'=>$payment_id['bill_id']));
            $aData['data'][$k]['pay_time'] = $pay_time['t_payed'];
            $obj_aftersales = app::get('aftersales')->model('return_product');
            $ord_id = $obj_aftersales->getRow('return_id',array('order_id'=>$v['order_id'],'status'=>'3','refund_type'=>'2'));
            if($ord_id){
                $aData['data'][$k]['need_send'] = 1;  // 需要退款
            }else{
                $aData['data'][$k]['need_send'] = 0;
            }
            $ord_id = $obj_aftersales->getRow('return_id',array('order_id'=>$v['order_id'],'status'=>'11','refund_type'=>'2'));
            if($ord_id){
                $aData['data'][$k]['need_edit'] = 1;  // 需要修改退货单
            }else{
                $aData['data'][$k]['need_edit'] = 0;
            }
            //预售截止支付时间
            if($v['order_type']=='preparesell'){
                $pre_order = app::get('preparesell')->model('prepare_order')->getList('*',array('order_id'=>$v['order_id']));
                $preinfo = app::get('preparesell')->model('preparesell')->getList("*",array('prepare_id'=>$pre_order[0]['prepare_id']));
                $aData['data'][$k]['prepare_info'] = array(
                    'begin_time'=>$preinfo[0]['begin_time'],//活动开始时间
                    'end_time'=>$preinfo[0]['end_time'],//活动结束时间
                    'end_time_first'=>$preinfo[0]['end_time_first'],//活动预付款支付结束时间
                    'end_time_final'=>$preinfo[0]['end_time_final'],//尾款支付结束时间
                    'order_timeout'=>$v['createtime'] + $preinfo[0]['timeout']*3600,//此订单最晚支付时间
                    );
            }
            //end
            foreach($v['goods_items'] as $k2=>$v2) {
                if( !$v2['product']['thumbnail_pic'] && !$oImage->getList("image_id",array('image_id'=>$v['image_default_id']))){
                    $aData['data'][$k]['goods_items'][$k2]['product']['pic_url'] = $imageDefault['S']['default_image'];
                }
                $thumbnail_pic_url = kernel::single('openapi_utils_image')->getimgbyid($aData['data'][$k]['goods_items'][$k2]['product']['thumbnail_pic']);
                $aData['data'][$k]['goods_items'][$k2]['product']['pic_url'] = $thumbnail_pic_url['url'];
                $act_id = '';
                //秒杀详细页参数
                switch($v['order_type']){
                    case 'spike':
                        $act_id = $applySObj->getOnActIdByGoodsId($v2['product']['goods_id']);
                        break;
                    case 'group':
                        $act_id = $applyGObj->getOnActIdByGoodsId($v2['product']['goods_id']);
                        break;
                    case 'score':
                        $act_id = $applyScoreObj->getOnActIdByGoodsId($v2['product']['goods_id']);
                        break;
                    case 'normal':
                        break;
                }
                
                if($act_id){
                    $aData['data'][$k]['goods_items'][$k2]['product']['args'] = array($v2['product']['goods_id'],'','',$act_id);
                }
            }

            //获取买家/卖家
            $obj_members = app::get('pam')->model('account');
            $obj_strman = app::get('business')->model('storemanger');
            $buy_name = $obj_strman->getRow('store_name',array('account_id'=>$v['member_id']));
            $aData['data'][$k]['buy_name'] = $buy_name['store_name'];

            
            $seller_id = $obj_strman->getRow('account_id,store_idcardname,store_name',array('store_id'=>$v['store_id']));
            $seller_name = $obj_members->getRow('login_name',array('account_id'=>$seller_id['account_id']));
            $aData['data'][$k]['seller_name'] = $seller_id['store_name'];
            $aData['data'][$k]['seller_real_name'] = $seller_id['store_idcardname'];
        }
        $result = array();
        foreach ($aData['data'] as $key => $order) {
            $or['order_id'] = $order['order_id'];
            $or['total_amount'] = $order['total_amount'];
            // $or['discount_value'] = $order['discount_value'];
            $or['cur_amount'] = $order['cur_amount'];
            $or['pay_status'] = $order['pay_status'];
            $or['ship_status'] = $order['ship_status'];
            // $or['is_delivery'] = $order['is_delivery'];
            $or['createtime'] = $order['createtime'];
            $or['currency'] = $order['currency'];
            // $or['last_modified'] = $order['last_modified'];
            // $or['shipping'] = $order['shipping'];
            $or['status'] = $order['status'];
            // $or['is_extend'] = $order['is_extend'];
            // $or['confirm'] = $order['confirm'];
            // $or['weight'] = $order['weight'];
            // $or['itemnum'] = $order['itemnum'];
            // $or['pmt_goods'] = $order['pmt_goods'];
            // $or['pmt_order'] = $order['pmt_order'];
            // $or['payed'] = $order['payed'];
            // $or['pay_time'] = $order['pay_time'];
            // $or['need_send'] = $order['need_send'];
            // $or['need_edit'] = $order['need_edit'];
            $or['seller_name'] = $order['seller_name'];
            $or['buy_name'] = $order['buy_name'];//$order['buy_name']; //由于app只解析了buy_name
            $or['order_type'] = $order['order_type'];
            if($or['order_type']=='preparesell'){
                $or['prepare_info'] = $order['prepare_info'];
            }
            $or['goods_items'] = array_merge($order['goods_items']);
            $result[] = $or;
        }
        if(count($result)==0){
            return $this->apiData(false,null,404,app::get('b2c')->_('没有更多了'));
        }
        return $this->apiData(true,array('orders'=>$result,'type'=>$type,'page_no'=>$nPage),200);
    }

    
    public function orderdetail($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $storeInfo = app::get('business')->model('storemanger')->getRow("*",array('account_id'=>$member_id));
        $store_id = $storeInfo['store_id'];
        $memberobj = kernel::single('b2c_api_site_member',$member_id);
        $res = $memberobj->orderdetail($params['order_id'],$err_msg);
        if(!$res){
            return $this->apiData(false,null,400,$err_msg);
        }
        //预售订单信息
        switch ($res['order']['order_type']) {//用来显示，根据国家切换语言
            case 'preparesell':
                $res['order']['promotion_type'] = 'prepare';
                break;
            
            default:
                
                break;
        }
        if($res['order']['order_type'] == 'preparesell'){
            $pre_order = app::get('preparesell')->model('prepare_order')->getList('*',array('order_id'=>$res['order']['order_id']));
            $preinfo = app::get('preparesell')->model('preparesell')->getList("*",array('prepare_id'=>$pre_order[0]['prepare_id']));
            $res['order']['promotion_info'] = array(
                'begin_time'=>$preinfo[0]['begin_time'],//活动开始时间
                'end_time'=>$preinfo[0]['end_time'],//活动结束时间
                'end_time_first'=>$preinfo[0]['end_time_first'],//活动预付款支付结束时间
                'end_time_final'=>$preinfo[0]['end_time_final'],//尾款支付结束时间
                'order_timeout'=>$res['order']['createtime'] + $preinfo[0]['timeout']*3600,//此订单最晚支付时间
                'preparesell_price'=>$pre_order[0]['preparesell_price'],//预售价格
                'first_payment'=>$pre_order[0]['first_payment'],//定金金额
                'final_payment'=>$pre_order[0]['final_payment'],//尾款
                'pay_status'=>$pre_order[0]['pay_status'],//支付状态 1、未支付 2、定金 3、尾款完成
            );
        }
        unset($res['request_url']);
        unset($res['order_chgpointmoney']);
        unset($res['discount_html']);
        unset($res['order']['title']);
        unset($res['order']['order_objects']);
        unset($res['order']['receiver']);
        unset($res['res_url']);
        unset($res['paymentlists']);
        $res['order']['goods_items'] = array_merge($res['order']['goods_items']);
        foreach ($res['order']['goods_items'] as $key => &$product) {
            $product['product']['thumbnail_pic'] = kernel::single('base_storager')->image_path($product['product']['thumbnail_pic'],'s');
        }
        //预售订单确认状况
        if($res['order']['order_type']=='preparesell'){
            $sql = "select pay_status,approve_status from " . DB_PREFIX . "preparesell_prepare_order where order_id=".$res['order']['order_id']." and store_id=".$store_id;
            $pay_status = kernel::database()->select($sql);
            $res['order']['approve_status'] = $pay_status[0]['approve_status'];
        }
        foreach ($res['orderlogs'] as $key => &$log) {
            $log['log_text'] = strip_tags($log['log_text']);
            $log['addon'] = urlencode($log['addon']);
        }
        return $this->apiData(true,$res,200);
    }

    
    public function prepare_order_approve($params,&$code,&$sub_msg){
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $db = kernel::database();
        $transaction_status = $db->beginTransaction();
        $order_id = $params['order_id'];
        $sql1 = "UPDATE " . DB_PREFIX . "preparesell_prepare_order SET approve_status='1' where order_id='".$order_id."' and status='true'";
        $mdl_orders = app::get('b2c')->model('orders');
        $order = $mdl_orders->getRow('*',array('order_id'=>$order_id));
        $sto= kernel::single("business_memberstore",$member_id);
        $data = $sto->storeinfo;
        $mdl_prepapre_order = app::get('preparesell')->model('prepare_order');
        if($data['store_id']==$order['store_id'] && $member_id){
            $mdl_prepapre_order->db->exec($sql1);
            $db->commit();
            return $this->apiData(true,null,200,app::get('b2c')->_('审核完成'));
        }else {
            $db->rollback();
            return $this->apiData(false,null,200,app::get('b2c')->_('无法审核'));
        }
    }
    
    public function offline_order($params,&$code,&$sub_msg){
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $nPage = $params['nPage'];
        $order_liset = app::get('b2c')->model('orders');
        //将数据插入到b2c_order_items表
        $order_items = app::get('b2c')->model('order_items'); 
        $mdl_products = app::get('b2c')->model('products');
        $mdl_goods = app::get('b2c')->model('goods');
        $base_storager = kernel::single('base_storager');
        $pagelimit = 10;
        $storeinfo = app::get('business')->model('storemanger')->getRow('store_id',array('account_id'=>$member_id));
        if($params['issale']){
            $filter = array('payment' => 'offline','store_id' => $storeinfo['store_id']);
        }else{
            $filter = array('payment' => 'offline','member_id' => $member_id);
        }
        $orders = $order_liset->getList("order_id,pay_status,status,total_amount,createtime",$filter,$pagelimit*($nPage-1),$pagelimit,'createtime desc');
        
        $pagedata = array();
        foreach($orders as $myinfo)
        {
            $info = $order_items->getList("order_id,name,nums,product_id,goods_id",array('order_id' => $myinfo['order_id']));
            $pdata = array();
            $pdata['order_id'] = $myinfo['order_id'];
            $pdata['totalprice'] = $myinfo['total_amount'];
            $pdata['createtime'] = date('Y-m-d H:i:s',$myinfo['createtime']);
            $pdata['pay_status'] =$myinfo['pay_status'];
            $pdata['status'] =$myinfo['status'];
            foreach ($info as  $value) {
                $spec = $mdl_products->getRow('spec_info',array('product_id'=>$value['product_id']));
                $image = $mdl_goods->getRow('image_default_id',array('goods_id'=>$value['goods_id']));
                $o = array();
                $o['name'] = $value['name']." ".$spec['spec_info'];
                $o['img'] = $base_storager->image_path($image['image_default_id'],'s');
                $o['nums'] = $value['nums'];
                $o['goods_id'] = $value['goods_id'];
                $pdata['goods_info'][] = $o;
            }
            $pagedata[] = $pdata;
        }

        if(empty($pagedata)){
            $sub_msg = app::get('b2c')->_('没有找到相应的订单！');
            return false;
        }
        return $this->apiData(true,$pagedata,200);
    }
    
    public function add_offline_order($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $storeinfo = app::get('business')->model('storemanger')->getRow('store_id',array('account_id'=>$member_id));
        $store_id = $storeinfo['store_id'];
        $mdl_goodsstore = app::get('b2c')->model('goods_store');
        $re = $mdl_goodsstore->getStoreGoodsList($store_id,'onlyHasProduct');
        $products = array();
        foreach($re as $k=>$v){
            foreach($v['product'] as $pk=>$pv){
                $p = array();
                $p['product_id'] = $pv['product_id'];
                $p['name'] = $pv['name'].$pv['spec_info'];
                $p['store_onsale'] = $pv['goods_store']['store_onsale'];
                if($params['issale']){
                    if($pv['goods_store']['store_onsale'] == 0){
                        unset($products[$pk]);
                        continue;
                    }
                }
                $products[] = $p;
            }
        }
        return $this->apiData(true,$products,200);
    }

    
    public function save_offline_order($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $issale = $params['issale']?true:false;
        $storeinfo = app::get('business')->model('storemanger')->getRow('store_id',array('account_id'=>$member_id));
        $store_id = $storeinfo['store_id'];
        $mdl_products = app::get('b2c')->model('products');
        $mdl_goods_store = app::get('b2c')->model('goods_store');
        $data = array();
        $params['createtime'] = $params['createtime']?$params['createtime']:time();
        //线下出库  
        foreach($params['goods'] as $key=>$p)
        {
            $product = $mdl_products->getRow('goods_id,name',array('product_id'=>$p['pid']));
            $goodsstore = $mdl_goods_store->getRow('store_onsale',array('product_id'=>$p['pid'],'store_id'=>$store_id));
            if($issale && $goodsstore['store_onsale'] < $p['num'])//库存小于所有相加的
            {
                return $this->apiData(false,null,400,'商品'.$product['name'].'销售总件数大于上架数量'.$goodsstore['store_onsale']);
            }

            $data[$p['pid']]['goodsid'] = $product['goods_id'];
            $data[$p['pid']]['productid'] = $p['pid'];
            $data[$p['pid']]['store'] = $goodsstore['store_onsale'];//库存不变
            $data[$p['pid']]['num']  = $p['num'];//卖出数量相加
            $data[$p['pid']]['price'] = $p['price'];
        }
        //如果有销售总数为0的产品则返回
        foreach ($data as $key => $mydata) 
        {
            if($mydata['num'] == 0)
            {
                unset($data[$key]);
            }
        }
        if(!$data)
        {
          return $this->apiData(false,null,400,app::get('b2c')->_('订单商品数量不能为0'));
        }

        $order = app::get('b2c')->model('orders');
        $order_id = $order->gen_id();

        //将数据插入到orders表
        $cur =  kernel::single('ectools_mdl_currency')->getDefault();
        $addrs = app::get('b2c')->model('member_addrs')->getList('*',array('member_id'=>$member_id,'def_addr'=>1));
        if(!empty($addrs)){
            $myaddr = $addrs[0];
        }else{
            $sadr = app::get('b2c')->model('member_addrs')->getList('*',array('member_id'=>$member_id));
            $myaddr = $sadr[0];
        }
        $order_insert = app::get('b2c')->model('orders');
        $order_data = array(
                'order_id' => $order_id,
                'total_amount'=> $params['totalprice'],
                'final_amount' => $params['totalprice'],
                'pay_status' => 1,
                'ship_status' => 0,
                'status' => 'finish',
                'createtime' =>$params['createtime'],
                'payment' => 'offline',
                'ship_area' => $myaddr['area'],
                'ship_addr' => $myaddr['addr'],
                'ship_tel' => $myaddr['tel'],
                'ship_zip' => $myaddr['zip'],
                'ship_mobile' => $myaddr['mobile'],
                'store_id' => $issale?$store_id:null,
                'approved' => 1,
                'confirm_status'=>1,
                'is_extend'=>0,
                'order_kind'=>'virtual',
                'order_type' => 'normal',
                'refund_status'=>'0',
                'payed'=>$params['totalprice'],
                'currency' => $cur['cur_code'],
                'memo'=>$params['memo'],
                'member_id'=>$issale?null:$member_id,
        );
        $rs = $order_insert->insert($order_data);

        //将数据插入到b2c_order_items表
        $order_items = app::get('b2c')->model('order_items'); 
        $productsname = app::get('b2c')->model('products');
        $order_objects = app::get('b2c')->model('order_objects');
        foreach ($data as $key => $mydata) 
        {
            $productsinfo = $productsname->getList('name,bn',array('product_id'=>$mydata['productid']));
            $product_name = $productsinfo[0]['name'];
            $order_obj_data  = array(
                'order_id' =>$order_id, 
                'obj_type'=>'goods',
                'obj_alias'=>'商品区块',
                'goods_id'=>$mydata['goodsid'],
                'bn'=>$productsinfo[0]['bn'],
                'name'=>$product_name,
                'price'=>$mydata['price'],
                'amount'=>$mydata['price']*$mydata['num'],
                'quantity'=>$mydata['num'],
                );
            $order_items_data = array(
                'order_id' => $order_id,
                //'obj_id'=> $totalprice,
                'product_id' => $mydata['productid'],
                'goods_id' => $mydata['goodsid'],
                'name' => $product_name,
                'nums' => $mydata['num'],
                
               );
            $rs1 = $order_objects->insert($order_obj_data);

            $rs2 = $order_items->insert($order_items_data);
            
            //关联库存
            $change_num = $issale?(0-$order_items_data['nums']):$order_items_data['nums'];
            $rs3 = $mdl_goods_store->updateStore($order_items_data['product_id'],$store_id,$change_num);
            if($issale){
                $rs4 = $mdl_goods_store->updateStoreOnSale($order_items_data['product_id'],$store_id,$change_num);
                kernel::single('b2c_goods_store')->log($store_id, $mydata['productid'], $order_id, '2', 0, $order_items_data['nums'],app::get('b2c')->_('线下出库'));
            }else{
                $rs4 = true;
                kernel::single('b2c_goods_store')->log($store_id, $mydata['productid'], $order_id, '1', $order_items_data['nums'], 0,app::get('b2c')->_('线下入库'));
            }
            if(!$rs || !$rs1 || !$rs2 || !$rs3 || !$rs4){
                return $this->apiData(false,null,400,app::get('b2c')->_('库存更新失败'));
            }
        }
        return $this->apiData(true,null,200,app::get('b2c')->_('订单生成成功'));
    }

}